package com.yang.library.client.menu;

import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.yang.library.bookenum.State;
import com.yang.library.bookenum.TCPEnum;
import com.yang.library.entry.Book;
import com.yang.library.util.AppContext;
import com.yang.library.util.Constant;
import com.yang.library.util.PrintUtils;

import java.io.*;
import java.net.Socket;
import java.nio.charset.StandardCharsets;
import java.util.List;

public class UserBookMenu implements Menu {
    private final ObjectMapper mapper = AppContext.getInstance().getMapper();
    private final Socket socket;

    public UserBookMenu(Socket socket) {
        this.socket = socket;
    }

    @Override
    public void start() {
        try {
            BufferedReader reader = new BufferedReader(new InputStreamReader(socket.getInputStream(), StandardCharsets.UTF_8));
            BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream(), StandardCharsets.UTF_8));
            while (true) {
                System.out.println("=========欢迎来到图书系统用户界面==========");
                System.out.println("1. 借阅图书");
                System.out.println("2. 归还图书");
                System.out.println("3. 显示自己的所有借阅图书");
                System.out.println("4. 显示所有图书");
                System.out.println("5. 图书系统用户管理界面(用户)");
                System.out.println("6. 退出图书系统用户界面");
                int type = PrintUtils.getIntInput(AppContext.getInstance().getScanner(), "请输入您的选择:");
                switch (type) {
                    case 1:
                        borrowBook(reader, writer);
                        break;
                    case 2:
                        returnBook(reader, writer);
                        break;
                    case 3:
                        getAllMyselfBorrowedBookByBorrower(reader, writer);
                        break;
                    case 4:
                        displayBooks(reader, writer);
                        break;
                    case 5:
                        new UserManagementMenu(socket).start();
                        break;
                    case 6:
                        return;
                    default:
                        System.out.println("输入错误，请重新输入！");
                }
            }
        } catch (Exception e) {
            System.out.println("图书管理系统用户界面异常");
            throw new RuntimeException(e);
        }
    }

    private void displayBooks(BufferedReader reader, BufferedWriter writer) throws Exception {
        writer.write(mapper.writeValueAsString(TCPEnum.QUERY_ALL_BOOK) + Constant.NEW_LINE);
        writer.flush();

        // 从服务端读取数据
        String resultMsg = reader.readLine();
        if (resultMsg == null) {
            System.out.println("请检查网络连接！");
            return;
        }
        List<Book> books = mapper.readValue(resultMsg, new TypeReference<>() {
        });
        if (books == null || books.isEmpty()) {
            System.out.println("没有借阅图书");
            return;
        }
        PrintUtils.printBooks(books);
    }

    private void getAllMyselfBorrowedBookByBorrower(BufferedReader reader, BufferedWriter writer) throws Exception {
        String userName = AppContext.getInstance().getUserName();
        writer.write(mapper.writeValueAsString(TCPEnum.QUERY_MY_BORROWED_BOOK) + Constant.NEW_LINE);
        writer.write(mapper.writeValueAsString(userName) + Constant.NEW_LINE);
        writer.flush();

        // 从服务端读取数据
        String resultMsg = reader.readLine();
        if (resultMsg == null) {
            System.out.println("请检查网络连接！");
            return;
        }
        List<Book> books = mapper.readValue(resultMsg, new TypeReference<>() {
        });
        if (books == null || books.isEmpty()) {
            System.out.println("没有借阅图书");
            return;
        }
        PrintUtils.printBooks(books);
    }

    private void returnBook(BufferedReader reader, BufferedWriter writer) throws Exception {
        String title = PrintUtils.getInput("请输入要归还的图书名称：");
        String userName = AppContext.getInstance().getUserName();

        // 向服务端发送请求
        writer.write(mapper.writeValueAsString(TCPEnum.RETURN_BOOK) + Constant.NEW_LINE);
        writer.write(mapper.writeValueAsString(title) + Constant.NEW_LINE);
        writer.write(mapper.writeValueAsString(userName) + Constant.NEW_LINE);
        writer.flush();

        // 获取服务器返回结果
        String result = reader.readLine();
        if (result == null) {
            System.out.println("请检查网络连接！");
            return;
        }
        State response = mapper.readValue(result, State.class);
        switch (response) {
            case SUCCESS:
                System.out.println("归还成功！");
                break;
            case FAILURE:
                System.out.println("归还失败！");
                break;
        }

    }

    private void borrowBook(BufferedReader reader, BufferedWriter writer) throws Exception {
        String title = PrintUtils.getInput("请输入要借阅的图书名称：");
        String userName = AppContext.getInstance().getUserName();
        // 向服务器发送借阅图书请求
        writer.write(mapper.writeValueAsString(TCPEnum.BORROW_BOOK) + Constant.NEW_LINE);
        writer.write(mapper.writeValueAsString(title) + Constant.NEW_LINE);
        writer.write(mapper.writeValueAsString(userName) + Constant.NEW_LINE);
        writer.flush();

        // 获取服务器返回结果
        String result = reader.readLine();
        if (result == null) {
            System.out.println("请检查网络连接！");
            return;
        }
        State response = mapper.readValue(result, State.class);
        switch (response) {
            case SUCCESS:
                System.out.println("借阅成功！");
                break;
            case FAILURE:
                System.out.println("借阅失败！");
                break;
        }
    }
}
